﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;

namespace OurEDAFM.Models
{
    public class WebClientHelper
    {
        public static WebClient Wc = new WebClient();        
        public static string GetJsonString(string url)
        {
            lock (LockClass.obj)
            {
                Wc.Encoding = System.Text.Encoding.UTF8;
                string result = Wc.DownloadString("http://musicfm.chinacloudsites.cn" + url);
                return result;
            }
        }

        public static string GetLikeSong(string id)
        {
            int value = GetRandomValue(0, 1);
            if (value == 1)
            {
                return WebClientHelper.GetJsonString("/Home/GetLikeMusic?id=" + id);
            }
            else {
                return GetLikeSongFromLocol(id);
            }
        }

        //从本地数据库读取一首随机歌曲
        public static string GetLikeSongFromLocol(string id)
        {
            using (FMDBEntities db = new FMDBEntities())
            {
                Guid userToken = new Guid(id);
                var songlist = db.MyLikeSongs.Where(a => a.UserToken == userToken).ToList();
                int value = GetRandomValue(0, songlist.Count-1);
                MyLikeSong song = songlist[value];
                GetSongModel result = new GetSongModel
                {
                    Like = true,
                    Msg = null,
                    Ok = true,
                    Song = song
                };
                return JsonConvert.SerializeObject(result);
            }
        }

        public static int GetRandomValue(int min, int max)
        {
            Random rad = new Random();
            int value = rad.Next(min, max+1);
            return value;
        }
    }
}